const router = require('express').Router();
const jwt = require('jsonwebtoken');
const { secret, expiresIn } = require('../config/jwt.config');
const User = require('../models/user.model');
const { success, error } = require('../utils/response');

// 注册
router.post('/register', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    const existingUser = await User.findOne({ where: { username } });
    if (existingUser) {
      return res.status(400).json(error('Username already exists'));
    }

    const user = await User.create({ username, password });
    res.json(success('Registration successful'));
  } catch (err) {
    res.status(500).json(error(err.message));
  }
});

// 登录
router.post('/login', async (req, res) => {
  const { username, password } = req.body;

  const user = await User.findOne({ where: { username } });
  if (!user || !bcrypt.compareSync(password, user.password)) {
    return res.status(401).json(error('Invalid credentials'));
  }

  const token = jwt.sign(
    { id: user.id, username: user.username },
    secret,
    { expiresIn }
  );

  res.json(success('Login successful', { token }));
});

module.exports = router;